package com.youdianda.service.impl;

import com.youdianda.constant.MessageConstant;
import com.youdianda.context.BaseContext;
import com.youdianda.dto.LoginDTO;
import com.youdianda.entity.YddUser;
import com.youdianda.exception.AccountNotFoundException;
import com.youdianda.exception.PasswordErrorException;
import com.youdianda.mapper.FrontIndexFgxMapper;
import com.youdianda.result.Result;
import com.youdianda.service.FrontIndexFgxService;
import com.youdianda.util.JwtUtil;
import com.youdianda.vo.YddUserInfoFgxVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class FrontIndexFgxServiceImpl implements FrontIndexFgxService {
    @Autowired
    private FrontIndexFgxMapper frontIndexMapper;

    @Override
    public Result login(LoginDTO dto) {
        String mobile = dto.getMobile();
        String password = dto.getPassword();

        //1、根据用户名查询数据库中的数据
        YddUser sysUser = frontIndexMapper.getByMobile(mobile);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (sysUser == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //对用户输入的明文密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(sysUser.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //直接用ID生成token
        String token = JwtUtil.getToken(Long.valueOf(sysUser.getId()));
        Map map = new HashMap();
        map.put("token",token);

        return Result.success(map);
    }

    @Override
    public Result getUserInfo() {
        YddUserInfoFgxVO yddUserInfoFgxVO = new YddUserInfoFgxVO();
        YddUser yddUser = frontIndexMapper.getUserInfo(BaseContext.getCurrentId());
        yddUserInfoFgxVO.setUserInfo(yddUser);
        yddUserInfoFgxVO.setArticleNum(frontIndexMapper.ArticleNum(BaseContext.getCurrentId()));
        yddUserInfoFgxVO.setCollectNum(frontIndexMapper.collectNum(BaseContext.getCurrentId(),1));
        yddUserInfoFgxVO.setZanNum(frontIndexMapper.collectNum(BaseContext.getCurrentId(),2));
        return Result.success(yddUserInfoFgxVO);
    }
}
